$(function () {
  let movieId = location.search.split("=")[1];
  $.getJSON("http://39.105.38.10:8081/movie/info", {
    id: movieId,
  }, function (res) {
    if (res.code === 200) {
      let data = res.data;
      /* 电影信息 */
      $("title, .con-left .moviename").text(data.title);
      const datetime = data.date;
      const earlest = datetime[datetime.length - 1].split('-')[0];
      const rateCount = Math.floor(Math.random() * 100000);
      $(".con-left h1 span").eq(1).text(`(${earlest})`);
      $(".subject .mainpic img").prop("src", `http://localhost:8888/mymovie/pages/proxy.php?url=${data.img}`);
      $(".subject .subject-info .directors").text(data.director);
      $(".subject .subject-info .scriptwriter").text(data.scriptwriter[0]);
      $(".subject .subject-info .actors").text(data.actor[0]);
      let movie_type = data.type.join(" / ");
      $(".subject .subject-info .genre").text(movie_type);
      $(".subject .subject-info .datetime").text(datetime.join(' / '));
      $(".subject .subject-info .runtime").text(data.runtime);

      /* 豆瓣评分 */
      $(".rating-left strong").text(data.rating || '暂无');
      $(".movie-rating").starRating({
        initialRating: (data.rating / 10 * 5).toFixed(1),
        starSize: 15,
        readOnly: true,
        useGradient: false,
        activeColor: "orange"
      });
      $(".douban-rating .rating-count").text(rateCount + "评价");

      /* 电影简介 */
      $(".movie-info p").text(data.summary);
      /* 加入我的影库 */
      $(".subject-info").append($('<button type="button" class="btn btn-primary" id="addToMy">加入我的影库</button>'));
      /* 切换账号时判断用户类型 */
      /* 判断登录的用户的身份并提供功能 */
      if (sessionStorage.getItem("type") == 0) {
        $("#addToMy").slideDown();
      }
      $("#addToMy").click(function () {
        $.post("addMovie.php", {
          movieId: movieId,
          title: data.title,
          summary: data.summary,
          rating: data.rating || 0.0,
          ratingCount: rateCount,
          scenarist: data.scriptwriter[0],
          image: data.img,
          runtime: data.runtime,
          director: data.director,
          cast: data.actor[0],
          year: earlest,
          movie_type: movie_type,
          playDate: datetime,
        }, function (res) {
          if (res.errorcode == 0) {
            alert(res.msg);
            location.href = "my-movies.html";
          } else {
            alert(res.msg);
          }
        }, "json");
      });
    } else {
      console.error(res);
    }
  })
});
